package com.droidclaimcustomer.helper.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class FileHandle {
	private static String ROOT_DIRECTORY = Environment.getExternalStorageDirectory().toString();

	public static String writeImage(Bitmap bitmap) {
		String filename = "";

		try {
			//Date date = new Date();
			//SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			//filename = sdf.format(date) + ".jpg";
			filename = FileHandle.getUnigueImageFileName();
			String destFilePath = FileHandle.getFilePath(filename);

			File file = new File(destFilePath);
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			final int BUFFER_SIZE = 1024 * 8;
			final BufferedOutputStream bos = new BufferedOutputStream(fos,
					BUFFER_SIZE);
			bitmap.compress(CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
			fos.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return filename;
	}

	public static Bitmap getImage(String filename) {
		Bitmap bitmap = null;
		try {
			String filePath = FileHandle.getFilePath(filename);
			File imgFile = new File(filePath);
			if (!imgFile.exists()) {
				throw new Exception("empty filename");
			}

			bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return bitmap;
	}
	
	public static String getUnigueImageFileName(){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String filename = sdf.format(date) + ".jpg";
		
		return filename;
	}
	
	public static String getFilePath(String fileName){
		return ROOT_DIRECTORY + "/" + fileName;
	}
	
	/*public static Bitmap getImageFromFilePath(String filePath){
		Bitmap bitmap = null;
		try {
			File imgFile = new File(filePath);
			if (!imgFile.exists()) {
				throw new Exception("empty filename");
			}

			bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return bitmap;
	}*/
}